<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
      <el-breadcrumb-item>产品配置</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <div slot="header">
        <span>基本信息</span>
      </div>
      <el-form
        :model="productForm"
        :rules="productFormRules"
        ref="productFormRef"
        label-width="100px"
      >
        <el-form-item label="一级分类" prop="first_code">
          <el-select
            v-model="productForm.first_code"
            placeholder="请选择"
            filterable
            clearable
            @change="changeSelect"
          >
            <el-option
              v-for="item in firstClasses"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" prop="type_code">
          <el-select
            v-model="productForm.type_code"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in secondClasses"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="产品类型" prop="type">
          <el-select
            v-model="productForm.type"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              key="1"
              label="服务产品"
              :value="typeof productForm.type == 'string' ? 1 + '' : 1"
            >
            </el-option>
            <el-option
              key="2"
              label="实物产品"
              :value="typeof productForm.type == 'string' ? 2 + '' : 2"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品规格" prop="specs">
          <el-input
            v-model="productForm.specs"
            placeholder="请输入，将用于客户端产品规格描述"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="服务形式"
          prop="service_form"
          v-show="productForm.type == 1"
          :rules="
            productForm.type == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="productForm.service_form"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              key="1"
              label="到店服务"
              :value="typeof productForm.service_form == 'string' ? 1 + '' : 1"
            >
            </el-option>
            <el-option
              key="2"
              label="上门服务"
              :value="typeof productForm.service_form == 'string' ? 2 + '' : 2"
            >
            </el-option>
            <el-option
              key="3"
              label="在线服务"
              :value="typeof productForm.service_form == 'string' ? 3 + '' : 3"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="服务时长"
          prop="service_length"
          v-show="productForm.type == 1"
          :rules="
            productForm.type == 1
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: servicehourValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            v-model="productForm.service_length"
            oninput="value = value.replace(/[^0-9.]/g, '')"
            placeholder="请输入，将用于客户端服务时长说明"
          >
            <template slot="append">小时</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="服务时间"
          prop="service_time"
          v-show="productForm.type == 1"
          :rules="
            productForm.type == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <div style="padding: 5px 10px 10px 10px; border: 1px solid #e5e7ec">
            <el-row
              style="margin-top: 5px"
              v-for="(time, index) in serviceTimeRange"
              :key="index"
            >
              <el-col :span="9">
                <el-time-select
                  placeholder="起始时间"
                  v-model="time.startTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '24:00'
                  }"
                >
                </el-time-select>
              </el-col>
              <el-col style="text-align: center" :span="2">至</el-col>
              <el-col :span="9">
                <el-time-select
                  placeholder="结束时间"
                  v-model="time.endTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '24:00',
                    minTime: time.startTime
                  }"
                >
                </el-time-select>
              </el-col>
              <el-col style="text-align: right" :span="4">
                <i
                  class="el-icon-plus"
                  v-show="index == serviceTimeRange.length - 1"
                  @click="addServiceTimeRange"
                ></i>
                &nbsp;
                <i
                  class="el-icon-delete"
                  v-show="index != 0"
                  @click="deleteServiceTimeRange"
                ></i>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="产品标准" prop="standard">
          <el-input
            type="textarea"
            v-model="productForm.standard"
            show-word-limit
            maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="productForm.remark"
            show-word-limit
            maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="$router.push('/product/configure')">
            取 消
          </el-button>
          <el-button class="theme-background-color" @click="saveProductInfo"
            >保 存</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var servicehourValid = (rule, value, callback) => {
      // console.log(value)
      value = value + ''
      if (!value) {
        return callback(new Error('服务时长不能为空'))
      } else if (value.indexOf('.') !== -1 && value.split('.').length > 2) {
        // 防止输入多个小数点
        callback(new Error('输入正确格式'))
      } else {
        // 不足补位
        value = Number(value).toFixed(1)
        this.productForm.service_length = value
        callback()
      }
    }
    return {
      productForm: {
        id: '',
        first_code: '',
        type_code: '',
        name: '',
        type: '',
        specs: '',
        service_form: '',
        service_length: '',
        service_time: '',
        standard: '',
        remark: ''
      },
      firstClasses: [],
      secondClasses: [],
      productFormRules: {
        first_code: [{ required: true, message: '请选择', trigger: 'change' }],
        type_code: [{ required: true, message: '请选择', trigger: 'change' }],
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        specs: [{ required: true, message: '请输入', trigger: 'blur' }],
        standard: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      servicehourValid,
      serviceTimeRange: [
        {
          startTime: '',
          endTime: ''
        },
        {
          startTime: '',
          endTime: ''
        }
      ]
    }
  },
  created() {
    this.getSelectData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/Data/find', {
        level: 1,
        code: 'product_type'
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.firstClasses = res.data.product_type
    },
    // 下拉框选中事件
    async changeSelect() {
      this.secondClasses = []
      this.productForm.type_code = ''
      var pid = this.productForm.first_code
      const { data: res } = await this.$http.post('/admin/Data/find', {
        level: 2,
        code: 'product_type',
        pid: pid
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取二级分类失败！')
      }
      this.secondClasses = res.data.product_type
    },
    // 点击按钮，添加产品
    saveProductInfo() {
      // console.log(this.finalServiceTime)
      this.productForm.service_time = this.finalServiceTime
      this.$refs.productFormRef.validate(async (valid) => {
        if (!valid) return
        if (parseInt(this.productForm.type) !== 1) {
          this.productForm.service_form = ''
          this.productForm.service_length = ''
          this.productForm.service_time = ''
        }
        // console.log(this.productForm)
        const { data: res } = await this.$http.post(
          'admin/Product/addProduct',
          this.productForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/product/configure')
      })
    },
    addServiceTimeRange() {
      this.serviceTimeRange.push({
        startTime: '',
        endTime: ''
      })
    },
    deleteServiceTimeRange() {
      this.serviceTimeRange.pop()
    }
  },
  computed: {
    finalServiceTime() {
      const value = []
      for (let i = 0; i < this.serviceTimeRange.length; i++) {
        if (
          this.serviceTimeRange[i].startTime &&
          this.serviceTimeRange[i].endTime
        ) {
          value.push(
            this.serviceTimeRange[i].startTime +
              '-' +
              this.serviceTimeRange[i].endTime
          )
        }
      }
      return value.join(',')
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
.el-select {
  width: 400px !important;
}
.el-date-editor {
  width: 100% !important;
}
</style>
